//index.js
//获取应用实例
const app = getApp()
import { formatTime } from "../../utils/util.js";
Page({
  data: {
    oneWeek:['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
    colorArrays: ["#aa92ff", "#ffc448", "#ffa27c", "#59f1a2", "#86b1fd", "#75ebea", "#DDA0DD"," 	 	#FFDEAD"],
    colorNullClass: "#E6E6FA",
    classList: [], // 周次排序列表
    dayList: [], // 指定某个周次的星期排序列表
    weekInput: null,
    minweek: 1,
    maxweek: null,
    index:0,
    nowWeek:1,
    startMonth:9,
    startDay:2,
  },
  findNowWeek:function(e){
    var time = formatTime(new Date());
    var month = time[5]+time[6];
    var day = time[8] + time[9];
    var nowMonth = month - this.data.startMonth;
    var nowDay = Math.abs(day-this.data.startDay);
    var week = Math.floor((nowDay + nowMonth * 30) / 7);
    if ((nowDay + nowMonth * 30) % 7 != 0 ){
      week = week + 1;
    }
    console.log(week);
    this.setData({
      week:week,
      nowWeek:week,
      index:week-1
    })

  },
  pickerKind: function (e) {
    var flag = parseInt(e.detail.value);
    console.log(flag);
    this.setData({
      weekInput:flag+1
    })
    this.onClickSearch();
    this.setData({
      index:flag
    })
  },
  onRefresh: function() {
    var that = this;
    if (that.data.username == 0) {
      wx.showModal({
        title: '提示',
        content: '未进行学生认证',
        cancelText: '再想想',
        confirmText: '去认证',
        success: res => {
          if (res.confirm) {
            wx.navigateTo({
              url: "/pages/zhjw/bindzhjw?is_class=1"
            })
          }
        }
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '重新导入后, 原有的课程数据将被全部覆盖, 确定要重新导入吗?',
        cancelText: '算了',
        confirmText: '重新导入',
        success: res => {
          if (res.confirm) {
            wx.showLoading({
              title: '导入课表中'
            })
            that.requestClassList(that.data.week, 1);
          }
        }
      })
    }
  },

  onLoad: function() { //   入口
  },
  onShow: function() {
    var that = this;
    var is_class = wx.getStorageSync('is_class');
    console.log(is_class);
    if(is_class == 1){
      var username = wx.getStorageSync('username');
      wx.setStorageSync('is_class', 0);
      that.setData({
        username: username
      })
      wx.showLoading({
        title: '导入课表中'
      })
      that.requestClassList(that.data.week, 1);
    }else{
      var is_Register = wx.getStorageSync('is_Register');
      if (is_Register) {
        var that = this;
        that.findNowWeek();
        var user_id = wx.getStorageSync('user_id');
        wx.request({
          url: 'https://api.geek51.cn/users/' + user_id + '/',
          method: "GET",
          success: function (res) {
            var username = res.data.data.student_id;
            that.setData({
              username: username
            })
            wx.setStorageSync('username', username);
            if (username != 0) {
              //直接从diandian服务器拿缓存即可
              that.onGetClasstable(username, that.data.week);
            } else {
              wx.showToast({
                title: '课表还未导入,赶快连接校园网导入课表吧',
                icon: 'none',
                duration: 2000
              });
            }
          }
        })
      } else {
        wx.showModal({
          title: '提示',
          content: '请先注册',
          showCancel: false,
          success: res => {
            if (res.confirm) {
              wx.switchTab({
                url: '/pages/my/my',
              })
            }
          }
        })
      }

    }
    
  },


  //从点点服务器拿redis缓存根据学号
  onGetClasstable: function(username, toWeek) {
    var that = this;
    wx.request({
      url: app.globalData.targetUrl + 'users/class/',
      data: {
        is_redis: 1,
        username: username
      },
      success: res => {
        if (res.data.error == 500) {
          that.setData({
            error: -1
          })
          wx.showToast({
            title: '赶快连接校园网,一键导入你的课表吧!',
            icon: 'none',
            duration: 3000
          });
        } else {
          var data = res.data.data;
          var classList = [];
          for (var week = 1; week <= 20; week++) {
            var temp_list = [];
            for (let course of data) {
              for (let classes of course.classes) {
                if (that.check_week(classes['周次'], week)) { // 如果属于对应周
                  classes["课程名"] = course["课程名"];
                  temp_list.push(classes);
                }
              }
            }
            classList.push(temp_list);
          }
          that.setData({
            classList: classList,
            error: 0
          });
          that.onSearchWeek(toWeek, classList);
        }
      }
    })
  },


  //手动长按删除课表课程
  onDeleteCourse: function(e) {
    var that = this;
    wx.showModal({
      title: '提示',
      content: '确定移除此课程？',
      success: res => {
        console.log(that.data.username);
        if (res.confirm) {
          wx.request({
            url: app.globalData.targetUrl + 'users/class/',
            method: 'GET',
            data: {
              "username": that.data.username,
              "courseName": e.currentTarget.dataset.coursename,
              "weekDay": e.currentTarget.dataset.weekday,
              "times": e.currentTarget.dataset.times,
              "is_redis": 1
            },
            success: function(res) {
              console.log(res.data.data);
              var data = res.data.data;
              var classList = [];
              for (var week = 1; week <= 20; week++) {
                var temp_list = [];
                for (let course of data) {
                  for (let classes of course.classes) {
                    if (that.check_week(classes['周次'], week)) { // 如果属于对应周
                      classes["课程名"] = course["课程名"];
                      temp_list.push(classes);
                    }
                  }
                }
                classList.push(temp_list);
              }
              that.setData({
                classList: classList
              });
              that.onSearchWeek(that.data.week, classList);
            }
          })
        }
      }
    })
  },

  // 冒泡排序
  bubbleSort: function(arr) {
    var len = arr.length;
    for (var i = 0; i < len; i++) {
      for (var j = 0; j < len - 1 - i; j++) {
        if (arr[j]["节次"] > arr[j + 1]["节次"]) { //相邻元素两两对比
          var temp = arr[j + 1]; //元素交换
          arr[j + 1] = arr[j];
          arr[j] = temp;
        }
      }
    }
    return arr;
  },
  // weeks: 周的范围 week: 周
  // 查询week这个周是否属于weeks的范围
  check_week: function(weeks, week) {
    var week_list = weeks.split(",")
    for (let k of week_list) {
      var idx = k.indexOf("-");
      if (idx != -1) { // 如果是范围
        var small = parseInt(k.substr(0, idx));
        var large = parseInt(k.substr(idx + 1));
        if (small <= week && week <= large) {
          return true;
        }
      } else {
        if (parseInt(k) == week) {
          return true;
        }
      }
    }
    return false;
  },

  // 给定某个周次下所有课程, 按星期进行分类
  getDayList: function(data) {
    var that = this;
    var day_list = [
      [],
      [],
      [],
      [],
      [],
      [],
      []
    ];
    for (let d of data) {
      day_list[d["星期"] - 1].push(d);
    }
    console.log("排序...")
    for (let dl of day_list) {
      dl = that.bubbleSort(dl);
    }
    // 打印测试
    return day_list;
  },

  // 输入周
  onWeekInput: function(e) {
    var that = this;
    that.setData({
      weekInput: e.detail.value
    })
  },

  // 点击查询
  onClickSearch: function(e) {
    var that = this;
    if (that.data.weekInput >= that.data.maxweek || that.data.weekInput < that.data.minweek) {
      wx.showModal({
        title: '查询错误',
        content: '你输入的周数无课，若想上课，向老师联系加课吧哈哈！',
        showCancel: false,
        success: res => {
          that.setData({
            weekInput: ''
          })
        }
      })
    } else {
      console.log(that.data.weekInput);
      var week = parseInt(that.data.weekInput);
      console.log(week);
      that.onGetClasstable(that.data.username, that.data.weekInput)
      that.setData({
        week: week,
        weekInput: ''
      });
    }
  },

  requestClassList: function(now_week, is_flush) {
    var that = this;
    console.log("username === " + that.data.username);
    wx.request({
      url: app.globalData.netUrl + 'api/zhjw/class/',
      method: 'GET',
      data: {
        "username": that.data.username,
        "is_flush": is_flush
      },
      success: function(res) {
        wx.hideLoading();
        if (res.statusCode == 7) {
          wx.showModal({
            title: '提示',
            content: '请将手机连接校园网后重试!',
            showCancel: false
          })
        } else {
          var data = res.data.data;
          that.onSaveClasstable(that.data.username, data);
          var classList = [];
          for (var week = 1; week <= 20; week++) {
            var temp_list = [];
            for (let course of data) {
              for (let classes of course.classes) {
                //console.log(classes);
                if (that.check_week(classes["周次"], week)) { // 如果属于对应周
                  classes["课程名"] = course["课程名"];
                  temp_list.push(classes);
                }
              }
            }
            classList.push(temp_list);
          }
          // classList: 按周次排列表

          that.setData({
            classList: classList
          });
          that.onSearchWeek(now_week, classList);
        }
      },
      fail: function (res) {
        wx.hideLoading();
        wx.showModal({
          title: '提示',
          content: '请将手机连接校园网后重试!',
          showCancel: false
        })
      }
    });
  },
  //将课表信息存入diandian服务器
  onSaveClasstable: function(username, data) {
    var that = this;
    wx.request({
      url: app.globalData.targetUrl + 'users/class/',
      method: 'POST',
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      data: {
        username: username,
        result_list: JSON.stringify(data),
        is_redis: 1
      },
      success: res => {
        console.log(res.data.data);
      }
    })
  },


  //  onSearchWeek 是对课程进行排版，传回渲染的函数
  onSearchWeek: function(now_week, data) {
    var that = this;
    // 指定周次, 获取星期排序列表
    console.log(data);
    for (var i = 0; i < data.length; i++) {
      if (data[i].length == 0) {
        that.setData({
          maxweek: i + 1
        })
        break;
      }
    }
    var array = [];
    for(var i = 1; i <= that.data.maxweek; i++){
      if(i == that.data.nowWeek){
        array.push("第" + i + "周(当前)");
      }else{
        array.push("第" + i + "周");
      }
    }
    that.setData({
      array:array
    })
    var day_list = that.getDayList(data[now_week - 1]);

    // 填充数据, 桶排序思想
    for (var i = 0; i < day_list.length; i++) {
      var bucket = [{}, {}, {}, {}, {}, {}];
      for (var j = 0; j < day_list[i].length; j++) {
        bucket[(parseInt(day_list[i][j]["节次"]) + 1) / 2 - 1] = day_list[i][j];
      }
      day_list[i] = bucket;
    }

    that.setData({
      dayList: day_list
    });
    console.log(day_list);
  },
  /*
  onImport:function(){
    var that=this;
    that.setData({
      is_show: false
    })
    if(that.data.username == 0){
      qq.showModal({
      title: '提示',
      content: '未进行教务认证',
      cancelText: '取消',
      confirmText: '认证',
      success: res => {
        if(res.confirm){
          qq.navigateTo({
            url: "/pages/zhjw/bindzhjw?is_class=1"
          })
        }
      }
    })
    }else{
      
     qq.showLoading({
       title: '加载中'
     })
      that.requestClassList(1,1);
    }
  },*/
  onaddCourse: function() {
    var that = this;
    if (that.data.username == 0) {
      wx.showModal({
        title: '提示',
        content: '未进行学生认证',
        cancelText: '再想想',
        confirmText: '去认证',
        success: res => {
          if (res.confirm) {
            wx.navigateTo({
              url: "/pages/zhjw/bindzhjw?is_class=1"
            })
          }
        }
      })
    } else {
      wx.navigateTo({
        url: "/pages/classable/addCourse"
      })
    }
  }
})